import Vue from 'vue'
import VueRouter from 'vue-router'
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'

Vue.use(VueRouter)

// 路由规则数组
const routes = [
  // 每个对象都表示一条路由规则
  {
    path: '/reg',
    component: Reg
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Main,
    redirect: '/home', // 路由重定向
    children: [
      {
        // 一般情况下子路由不以 / 开头, 会拼接前面的父路由  /home
        // 如果非要以 / 开头, 则不拼接前面的父路由  /home
        path: 'home',
        component: Home
      },
      {
        path: 'user-info',
        component: UserInfo
      },
      {
        path: 'user-avatar',
        component: UserAvatar
      },
      {
        path: 'user-pwd',
        component: UserPwd
      },
      {
        path: 'art-cate',
        component: ArtCate
      },
      {
        path: 'art-list',
        component: ArtList
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 添加全局前置守卫
// 注意事项: 必须要调用 next() 否则就瘫痪了
// to: 到哪里去
// from: 从哪里来
// next: 是否放行, 放行: next() 不放行: next(false) 强制跳转: next('路径')
router.beforeEach((to, from, next) => {
  // 需求: 如果没有登录不允许去首页, 但允许去登录页 或 注册页
  // 如果没有登录就去登录页
  // 登录的判断依据: 是否有 token
  const token = store.state.user.token
  // console.log(to, from)
  // if (to.path === '/login') {
  //   return next()
  // }

  const whiteList = ['/login', '/reg']

  // 条件1: 没登录
  // 条件2 & 3: 去的页面既不是登录也不是注册
  // if (!token && to.path !== '/login' && to.path !== '/reg') {
  // if (!token && 不在白名单) {
  // whiteList.includes: 数组方法, 判断指定的元素是否在数组中, 返回一个布尔值
  // whiteList.indexOf('/404') -1
  if (!token && !whiteList.includes(to.path)) {
    // 打回登录页
    next('/login')

    // 提醒用户未登录
    Vue.prototype.$message.error('您还未登陆哦!亲!')
  } else {
    next()
  }
})

export default router
